﻿/**
 * jiangliwu 
 * 2016年03月31日16:20:11
 * 基本开发框架
**/
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;



namespace VFramework
{

	/// <summary>
	/// 框架初始类，放在主camera下面
	/// 该类为单例，放入多个会异常
	/// </summary>
	public class VFrameworkInitializer : MonoBehaviour
	{

		public bool showFPS = true;
		public bool screenLogClose = false;
		public bool openMachineController = true;
		public bool lockFrame60 = true;

		private static int _vframeworkCounter = 0;



		void Awake ()
		{
			if (++_vframeworkCounter > 1) {
				throw new UnityException ("VFramework only attach on Camera once!");
			}

			if (GetComponent<Camera> () == null) {
				throw new UnityException ("VFramework only attach on Camera!");
			}

			beforeInit ();
			init ();

			if (lockFrame60) {
				Application.targetFrameRate = 60;
			}
		}

		void Start ()
		{

		}



		void beforeInit ()
		{

			// fps
			if (showFPS) {
				gameObject.AddComponent<FPSCounter> ();
			}


			// logger
			VLogger.getInstance ().setLogger (new ConsoleLogger (), new LogLevel []{
				LogLevel.DEBUG,LogLevel.WARN,LogLevel.INFO,LogLevel.ERROR
			});
			VLogger.getInstance ().setLogger (ScreenLogger.create (gameObject), new LogLevel []{
				LogLevel.DEBUG,LogLevel.WARN,LogLevel.INFO,LogLevel.ERROR
			});

			VLogger.screenClose (screenLogClose);

			// music, effect , light
			SystemMgr.getInstance ().initEvent ();
			SystemMgr.getInstance ().initAudio (GetComponent<Camera> ());

			VLogger.info ("VFrameworkInitializer::beforeInit success !!!");




			//extensions

			if (openMachineController) {

				gameObject.AddComponent<MachineObject> ();
				MController.g ().connect ();

				MachineObject.pushCallback (MachineObject.BIG_MIDDLE_BTN_ID, delegate {
					EventMgr.getInstance ().dispatchEvent (FrameEvents.MACHINE_BIG_BTN_EVENT);
				});
			}

		}

		void init ()
		{

			/// <summary>
			/// 场景跳转事件
			/// </summary>
			EventMgr.getInstance ().addEvent (FrameEvents.LOAD_SCENE_BY_NAME, delegate (EventData eventData) {
				string name = (string)ArgsWarp.getValue ("name", eventData.data);
				bool asyn = (bool)ArgsWarp.getValue ("asyn", eventData.data);

				release ();  //清理
				if (asyn == true) {
					VConfig.next_scene = name;
					SceneManager.LoadScene ("load");
					return null;
				} else {
					SceneManager.LoadScene (name);
					return null;
				}
			});

			VLogger.info ("VFrameworkInitializer::init success !!!");
		}


		void Update ()
		{

		}

		/// <summary>
		/// Release this instance.
		/// </summary>
		void release ()
		{
			_vframeworkCounter = 0;

			SystemMgr.getInstance ().release ();
			EventMgr.getInstance ().release ();

			if (openMachineController) {
				MController.g ().release ();
			}

			VLogger.info ("VFrameworkInitializer::release success !!!");
			VLogger.getInstance ().release ();
		}

	}

}
